#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLE2902.h>

// 服务和特征UUID
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

// 全局变量
bool isConnected = false;  // 是否连接
BLEServer *pServer = nullptr; // 创建服务对象
BLECharacteristic* pCharacteristic = nullptr;//全局特征对象
unsigned long lastNotifyTime = 0;

// 自定义特征回调类，处理读写事件
class MyCharacteristicCallbacks : public BLECharacteristicCallbacks
{
    // 蓝牙串口接收到手机写数据
    void onWrite(BLECharacteristic *pCharacteristic)
    {                                                
      //获取特征值              
      String data = pCharacteristic->getValue();
      Serial.println(data.c_str());
    }
};

// 自定义服务器回调类，处理连接状态
class MyServerCallbacks : public BLEServerCallbacks
{
    //蓝牙连接
    void onConnect(BLEServer *pServer)
    {
        Serial.println("主机已连接");
        isConnected = true;
    };
    //蓝牙断开
    void onDisconnect(BLEServer *pServer)
    {
        Serial.println("主机已断开");
        isConnected = false;
        BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
        BLEDevice::startAdvertising();//开始广播
    }
};

void setup()
{
    // 初始化串口和BLE设备
    Serial.begin(115200);
    BLEDevice::init("ESP32_BLE");
    esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_ADV, ESP_PWR_LVL_P9);

    // 创建BLE服务器
    pServer = BLEDevice::createServer();
    //设置服务器回调
    pServer->setCallbacks(new MyServerCallbacks());

    //创建一个服务
    BLEService *pService = pServer->createService(SERVICE_UUID);
    // 创建特征和属性
    pCharacteristic = pService->createCharacteristic(
        CHARACTERISTIC_UUID,
        BLECharacteristic::PROPERTY_READ |//(手机)读数据权限
        BLECharacteristic::PROPERTY_WRITE |//(手机)写数据权限
        BLECharacteristic::PROPERTY_NOTIFY//ESP32通知权限
    );
    //添加特征值
    pCharacteristic->setValue("hello world");
    // 添加CCCD描述符，使能通知
    pCharacteristic->addDescriptor(new BLE2902());
    // 设置特征回调
    pCharacteristic->setCallbacks(new MyCharacteristicCallbacks());
    // 启动服务
    pService->start();

    // 启动广播
    BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
    BLEDevice::startAdvertising();//开始广播
    Serial.println("蓝牙开始广播");
}

int index_num = 0;
void loop()
{
    // 如果处于连接状态下
    if (isConnected) { 
        //间隔1S
        if (millis() - lastNotifyTime >= 100) {
            lastNotifyTime = millis();
            index_num++;
            String data = String(index_num);
            pCharacteristic->setValue(data);
            pCharacteristic->notify();  // 发送通知（内容固定为"hello"）
            Serial.println("发送通知:" + data);
        }

        // if (Serial.available())
        // {
        //     String data = Serial.readStringUntil('\n'); // 去除换行符
        //     Serial.println("发送:" + data);                       // 测试

        //     pCharacteristic->setValue(data);
        //     pCharacteristic->notify();  // 发送通知（内容固定为"hello"）
        // }
    }
}
